package com.demo.reports.demo6200sphone;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.device.ScanManager;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.demo.reports.demo6200sphone.response.CheckTicketResponse;
import com.demo.reports.demo6200sphone.response.GateListResponse;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

import java.util.List;
import java.util.Locale;

import lib.kingja.switchbutton.SwitchMultiButton;
import okhttp3.Call;

public class MainActivityOld extends AppCompatActivity implements View.OnClickListener {
    /********************************扫码驱动相关*************************************/
    private int periodCount = 3;                //默认3s检一次
    public boolean bNeedCheckTicket = true;    //检票标志位
    private String barcodeStr;
    private ScanManager mScanManager;
    private boolean scanPowerState;
    private boolean lockTrigglerState;
    private int type;
    protected final static String SCAN_ACTION = "urovo.rcv.message";//扫描结束action
    /********************************扫码驱动相关*************************************/

    /**********************语音合成**********************/
    //语音引擎
    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {
                /*
               int supported = mSpeech.setLanguage(Locale.ENGLISH);
                if ((supported != TextToSpeech.LANG_AVAILABLE) && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)) {
                   Toast.makeText(MainActivity.this, "不支持当前语言！", Toast.LENGTH_SHORT).show();
                   Log.i(TAG, "onInit: 支持当前选择语言");
               }else{

               }
               */
                Log.i(TAG, "onInit: TTS引擎初始化成功");
            } else {
                Log.i(TAG, "onInit: TTS引擎初始化失败");
            }
        }
    }

    private static final String TAG = "MainActivity";
    private TextToSpeech mSpeech = null;
    private static float m_voice_speed = 1.0f;   //合成语音的语速
    private static float m_voice_pitch = 1.0f;   //合成语音的语调
    /****************************************************/


    private ImageView img_ip;
    private boolean isIPset;
    private ImageView img_link;
    private ImageView img_status;
    private TextView tv_terminal, tv_ticketNO, tv_time, tv_status, tv_name, tv_people;
    private TextView tv_pCount;
    private TextView tv_delete;
    private PopupWindow popupWindow;
    private int screenWidth, screenHeight;
    SwitchMultiButton mSwitchMultiButton;
    private EditText et_input;
    SharedPreferences sp;
    SharedPreferences.Editor edit;
    private TextView tv1, tv2;
    int count = 0;
    GateListResponse gateListResponse;
    List<GateListResponse.GateInfoListBean> list;

    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            //得到二维码后锁住Trigger

            if(bNeedCheckTicket)
            {
                bNeedCheckTicket = false;
                //清空显示
//                clearTiketInfo();

                // TODO Auto-generated method stub
                byte[] barocode = intent.getByteArrayExtra("barocode");
                System.out.print(barocode);
                int barocodelen = intent.getIntExtra("length", 0);
                byte temp = intent.getByteExtra("barcodeType", (byte) 0);
                barcodeStr = new String(barocode, 0, barocodelen);

                //gLogger.debug("barcodeStr:" + barcodeStr);

//                strTicketCode.setText(barcodeStr);

                if (barcodeStr != null && !barcodeStr.equals("") )//&& barcodeStrAgain != barcodeStr
                {
                checkQRCode(barcodeStr);
                }
                //定时线程启动下次检票
                TriggerThread();
            }else{
//                setSysstatus("请稍等...");
                ToastUtil.showToast("请稍等...");
            }
        }

    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE); // 去掉标题栏
        setContentView(R.layout.activity_main);

        sp = getSharedPreferences("position", Context.MODE_PRIVATE);
        edit = sp.edit();
        //获取sp中存储的扫描票数
        count = sp.getInt("count", 0);

        //初始化扫描器
        initScan();
        //意图过滤器和广播注册
        IntentFilter filter = new IntentFilter();
        filter.addAction(SCAN_ACTION);
        //  unregisterReceiver(mScanReceiver);
        registerReceiver(mScanReceiver, filter);
        initView();

        //获取TTS引擎
        mSpeech = new TextToSpeech(MainActivityOld.this, new TTSListener());
        isIPset = sp.getBoolean("isIPset", false);
        if (!sp.getString("ip", "").equals("")) {
//            拼接IP地址
            BaseURL.SERVER_URL = sp.getString("ip", "");
            BaseURL.SERVER_URL = "http://" + BaseURL.SERVER_URL;
            getGateList();
        }

    }
    private void initView() {

        WindowManager manager = (WindowManager) getBaseContext().getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        Point point = new Point();
        if (Build.VERSION.SDK_INT < 17) {
            display.getSize(point);
        } else {
            display.getRealSize(point);
        }
        screenWidth = point.x;
        screenHeight = point.y;

        mSwitchMultiButton = (SwitchMultiButton) findViewById(R.id.switchmultibutton);
        mSwitchMultiButton.setText("全检", "部分检").setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onSwitch(int position, String tabText) {
                if (position == 1) {
                    et_input.setText("");
                    et_input.setEnabled(true);
                    et_input.setBackground(new ColorDrawable(Color.parseColor("#ffffff")));

                } else {
                    et_input.setText("");
                    et_input.setBackground(new ColorDrawable(0xaa000000));
                    et_input.setEnabled(false);
                }
            }
        });


        tv1 = (TextView) findViewById(R.id.unbind_tv1);
        tv2 = (TextView) findViewById(R.id.unbind_tv2);
        img_link = (ImageView) findViewById(R.id.ma_img_link);
        img_status = (ImageView) findViewById(R.id.img_status);
        tv_terminal = (TextView) findViewById(R.id.ma_tv_terminal);
        tv_ticketNO = (TextView) findViewById(R.id.ma_tv_ticketNO);
        tv_time = (TextView) findViewById(R.id.ma_tv_time);
        tv_status = (TextView) findViewById(R.id.ma_tv_status);
        tv_name = (TextView) findViewById(R.id.ma_tv_name);
        tv_people = (TextView) findViewById(R.id.ma_tv_people);
        tv_pCount = (TextView) findViewById(R.id.ma_tv_pCount);
        tv_delete = (TextView) findViewById(R.id.ma_tv_delete);
        et_input = (EditText) findViewById(R.id.ma_et_input);
        img_ip = (ImageView) findViewById(R.id.img_ip);
        tv_terminal.setText(sp.getString("gateNo", ""));
        tv_pCount.setText("" + count);
        img_ip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final EditText et = new EditText(MainActivityOld.this);
                et.setHint("192.168.8.8:8888/Base");
                String digital = "0123456789.:/qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
                et.setKeyListener(DigitsKeyListener.getInstance(digital));
//                若已经保存ip，则显示
                if (!sp.getString("ip", "").equals("")) {
                    et.setText(sp.getString("ip", ""));
                }
                new AlertDialog.Builder(MainActivityOld.this)
                        .setMessage("请输入ip地址")
                        .setView(et)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                edit.putString("ip", et.getText().toString().trim());
                                edit.commit();
//                                拼接IP地址
                                BaseURL.SERVER_URL = sp.getString("ip", "");
                                BaseURL.SERVER_URL = "http://" + BaseURL.SERVER_URL;
                                isIPset = true;
                                edit.putBoolean("isIPset", isIPset);
                                edit.commit();

                                getGateList();
                                ToastUtil.showToast("设置IP: " + et.getText().toString() + " 成功");
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {

                            }
                        }).show();
            }
        });
        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(MainActivityOld.this)
                        .setMessage("清空检票人数")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                count = 0;
                                edit.putInt("count", 0);
                                edit.commit();
                                tv_pCount.setText("" + count);
                                ToastUtil.showToast("清空人数成功");
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {

                            }
                        }).show();

            }
        });

        et_input.setOnKeyListener(new View.OnKeyListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Log.d("key", "" + keyCode);
                if (keyCode == 66) {
                    Log.d("key", "" + keyCode);
                    et_input.setText("");
                    et_input.setBackground(new ColorDrawable(0xaa000000));
                    et_input.setEnabled(false);
                    mSwitchMultiButton.setSelectedTab(0);
                }
                return false;
            }
        });

        img_link.setOnClickListener(this);


//        键盘监听事件
        SoftKeyBoardListener.setListener(MainActivityOld.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            //            键盘显示
            @Override
            public void keyBoardShow(int height) {
//                Toast.makeText(AdjustResizeActivity.this, "键盘显示 高度" + height, Toast.LENGTH_SHORT).show();
            }

            //            键盘隐藏
            @Override
            public void keyBoardHide(int height) {
//                Toast.makeText(AdjustResizeActivity.this, "键盘隐藏 高度" + height, Toast.LENGTH_SHORT).show();
                //键盘隐藏后，设置switch为全检（false）。


            }
        });

    }
    //播放合成语音
    public void PlayAudioFile(String str)
    {
        //设置中文
        int supported = mSpeech.setLanguage(Locale.CHINA);
        mSpeech.setSpeechRate(m_voice_speed);
        mSpeech.setPitch(m_voice_pitch);

        if((supported != TextToSpeech.LANG_AVAILABLE) && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)){
            //语言设置失败
            Log.i(TAG, "中文设置失败");
        }
        else{
            Log.i(TAG, "中文设置成功");
        }
        //mSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
        mSpeech.speak(str,TextToSpeech.QUEUE_ADD,null);
    }
    public void ShowMsg(String Msg, int type, int PlayOrNot)
    {
        PlayAudioFile(Msg);


    }
    //定时器实现防连刷的功能
    public void TriggerThread()
    {
        new Thread(new Runnable(){
            @Override
            public void run() {
                long count = 0;
                while(true)
                {
                    if(periodCount <= count)
                    {
                        bNeedCheckTicket = true;
//                        setSysstatus("请检票");
//                        ToastUtil.showToast("请检票");
                        break;
                    }

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    count++;
                }
            }
        }).start();
    }
//    //设置系统状态
//    public void setSysstatus(String str)
//    {
//        strSysstatus = str;
//        SysStatus.post(new Runnable() {
//            @Override
//            public void run() {
//                SysStatus.setText(strSysstatus);
//            }
//        });
//    }
private void initScan() {
    // TODO Auto-generated method stub
    mScanManager = new ScanManager();
    type = mScanManager.getScannerType();
    switch(type) {
        case 1:
            break;
        case 2:
            break;
        case 3:
            break;
        case 4:
            break;
    }
    scanPowerState =  mScanManager.getScannerState();
    if (!scanPowerState) {
        mScanManager.openScanner();
    }
    lockTrigglerState = mScanManager.getTriggerLockState();
    if (lockTrigglerState) {
        mScanManager.unlockTriggler();
    }
    mScanManager.switchOutputMode(0);
}

    @Override
    public void onClick(View v) {
        if (!isIPset) {
            ToastUtil.showToast("请设置ip地址");
            return;
        }
        View view = View.inflate(this, R.layout.popupwindow_ma_layout, null); //引入布局
        //获取PopupWindow中View的宽高
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

        //将布局view传参给popupwindow
        popupWindow = new PopupWindow(view, screenWidth, screenHeight * 3 / 5);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xaa000000));//设置背景

        popupWindow.setFocusable(true);//popupwindow设置焦点
        popupWindow.setOutsideTouchable(true);//点击外面窗口消失
        popupWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

        setOnPopupViewClick(view);
        popupWindow.setAnimationStyle(android.R.style.Animation_Translucent);//设置动画
    }
    private void setOnPopupViewClick(View view) {

        ImageView img_close = (ImageView) view.findViewById(R.id.pop_img_close);
        final ListView pop_list = (ListView) view.findViewById(R.id.pop_list);
        final PopListAdapter adapter;
        if (list != null && list.size() > 0) {
            adapter = new PopListAdapter(getBaseContext(), list);
            pop_list.setAdapter(adapter);
        } else {
            ToastUtil.showToast("闸机列表为空，请检查IP设置");
            return;
        }

        img_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        pop_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                edit.putInt("position", position);
//                edit.putString("gateName", list.get(position).getGateName());
                edit.putString("gateNo", list.get(position).getGateNo());

                edit.commit();

                tv_terminal.setText(list.get(position).getGateNo());
                adapter.notifyDataSetChanged();
                ToastUtil.showToast("选中 " + list.get(position).getGateNo() + " 成功");
            }
        });
    }
    private void getGateList() {
//        清空缓存，用于及时更新数据
        if (list != null) {
            list = null;
        }

        if (!isIPset) {
            ToastUtil.showToast("请设置ip地址");
            return;
        }

        String url = BaseURL.SERVER_URL + BaseURL.UNBINDPHONELIST;
        OkHttpUtils
                .get()
                .url(url)
                .addParams("userName", "admin")
                .addParams("password", "888888")
                .addParams("sign", "DDCA01EF3FF8B6C429D8FE406740539F")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtil.showToast("获取闸机列表失败，请检查ip设置");
                    }

                    @Override
                    public void onResponse(String response, int id) {

                        try {
                            gateListResponse = new Gson().fromJson(response, GateListResponse.class);
                            if (gateListResponse.getCode().equals("0")) {

                                list = gateListResponse.getGateInfoList();

                            } else {
                                ToastUtil.showToast("" + gateListResponse.getMessage());
                            }
                        } catch (Exception e) {
                            ToastUtil.showToast("获取闸机列表失败");

                        }
                    }

                });
    }
    public void clearText() {
        tv_ticketNO.setText("");
        tv_time.setText("");
        tv_status.setText("");
        tv_name.setText("");
        tv_people.setText("");
    }
    private void checkQRCode(final String barcodeStr) {

        clearText();
        if (!isIPset) {
            ToastUtil.showToast("请设置ip地址");
            return;
        }
//        判断输入框是否输入了数据
        if (et_input.getText().toString().trim().length()>0) {
            int value= Integer.valueOf(et_input.getText().toString().trim());
            if (value<=0||value>1000) {
                ToastUtil.showToast("请输入合法数据");
                return;
            }
        }


        String url = BaseURL.SERVER_URL + BaseURL.CHECKTICKET;
        String sp_gateN0 = sp.getString("gateNo", "");
        if ("".equals(sp_gateN0)) {
            ToastUtil.showToast("请选择设备终端");
            return;
        }
        if (mSwitchMultiButton.getSelectedTab() == 1 && et_input.getText().toString().trim().equals("")) {
            ToastUtil.showToast("请输入检票数量");
            return;
        }

        int checkCount = mSwitchMultiButton.getSelectedTab() == 1 ? Integer.valueOf(et_input.getText().toString().trim()) : -1;


        try {
            OkHttpUtils
                    .get()
                    .url(url)
                    .addParams("ticketNo", barcodeStr)
                    .addParams("userName", "admin")
                    .addParams("password", "888888")
                    .addParams("gateNo", sp_gateN0)
                    .addParams("checkCount", "" + checkCount)
                    .addParams("sign", "FC2C7EC3C74BC8EA2A5F4C894323B5B7")
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            ToastUtil.showToast("检票失败");
                        }

                        @Override
                        public void onResponse(String response, int id) {

                            //将String类型转换成json类型
                            JSONObject object = null;
                            try {
                                object = XML.toJSONObject(response);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            String jsonData = object.toString();        //转换为json字符串。
                            Log.d("", "" + jsonData);
                            CheckTicketResponse response1 = new Gson().fromJson(jsonData, CheckTicketResponse.class);
                            if (0 == (response1.getCheckTicketMessageResult().getCode())) {

                                tv_terminal.setText(sp.getString("gateNo", ""));
                                tv_ticketNO.setText(barcodeStr);
                                tv_time.setText(response1.getCheckTicketMessageResult().getCheckTime());
                                tv_status.setText(response1.getCheckTicketMessageResult().getMsg());
                                tv_name.setText(response1.getCheckTicketMessageResult().getTicketName());
                                tv_people.setText("" + response1.getCheckTicketMessageResult().getTotalMaxNumber());

                                count = count + response1.getCheckTicketMessageResult().getTotalMaxNumber();
                                tv_pCount.setText("" + count);
                                img_status.setImageResource(R.drawable.background_pass);
                                ShowMsg(response1.getCheckTicketMessageResult().getGateSoundID(), 0, 0);
                                mSwitchMultiButton.setSelectedTab(0);

                            } else {
                                img_status.setImageResource(R.drawable.background_error);
                                ShowMsg(response1.getCheckTicketMessageResult().getGateSoundID(), 0, 0);
                                mSwitchMultiButton.setSelectedTab(0);


                            }

                        }

                    });
        }catch (Exception e){
            ToastUtil.showToast(e.toString());
        }

    }
    @Override
    protected void onPause() {
        super.onPause();
        edit.putInt("count", count);
        edit.commit();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();

        edit.putInt("count", count);
        edit.commit();


        unregisterReceiver(mScanReceiver);

        //清空所有Cookie
        CookieSyncManager.createInstance(this);  //Create a singleton CookieSyncManager within a context
        CookieManager cookieManager = CookieManager.getInstance(); // the singleton CookieManager instance
        cookieManager.removeAllCookie();// Removes all cookies.
        CookieSyncManager.getInstance().sync(); // forces sync manager to sync now
    }

}
